

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Fly542">
  <meta name="keywords" content="">
  
    <meta name="description" content="1. 日历时间(Calendar Time)unix系统内部对时间的表示方式均是以自Epoch以来的秒数来度量的。Epoch即通用协调时间(UTC, 也称为格林威治标准时间，或GMT)的1970年1月1日早晨零点。 日历时间存储在类型为 time_t  的变量中。 1.1 gettimeofday() 可与tv指向的缓冲区中返回日历时间 int gettimeofday(struct timeva">
<meta property="og:type" content="article">
<meta property="og:title" content="时间及其转换">
<meta property="og:url" content="http://fly542.cn/2020/11/17/03%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91/01c_cpp/05%E6%97%B6%E9%97%B4/index.html">
<meta property="og:site_name" content="Fly542 技术沉淀">
<meta property="og:description" content="1. 日历时间(Calendar Time)unix系统内部对时间的表示方式均是以自Epoch以来的秒数来度量的。Epoch即通用协调时间(UTC, 也称为格林威治标准时间，或GMT)的1970年1月1日早晨零点。 日历时间存储在类型为 time_t  的变量中。 1.1 gettimeofday() 可与tv指向的缓冲区中返回日历时间 int gettimeofday(struct timeva">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://fly542.cn/2020/11/17/03%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91/01c_cpp/05%E6%97%B6%E9%97%B4/time.png">
<meta property="article:published_time" content="2020-11-17T04:22:13.000Z">
<meta property="article:modified_time" content="2022-12-30T03:33:01.332Z">
<meta property="article:author" content="Fly542">
<meta property="article:tag" content="c++">
<meta property="article:tag" content="c">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="http://fly542.cn/2020/11/17/03%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91/01c_cpp/05%E6%97%B6%E9%97%B4/time.png">
  
  
  <title>时间及其转换 - Fly542 技术沉淀</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"fly542.cn","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 6.0.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Fly542 技术沉淀</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="时间及其转换">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2020-11-17 12:22" pubdate>
        2020年11月17日 中午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      1.8k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      16 分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">时间及其转换</h1>
            
            <div class="markdown-body">
              <h1 id="1-日历时间-Calendar-Time"><a href="#1-日历时间-Calendar-Time" class="headerlink" title="1. 日历时间(Calendar Time)"></a>1. 日历时间(Calendar Time)</h1><p>unix系统内部对时间的表示方式均是以自Epoch以来的秒数来度量的。Epoch即通用协调时间(UTC, 也称为格林威治标准时间，或GMT)的1970年1月1日早晨零点。</p>
<p>日历时间存储在类型为 <strong>time_t</strong>  的变量中。</p>
<h2 id="1-1-gettimeofday"><a href="#1-1-gettimeofday" class="headerlink" title="1.1 gettimeofday()"></a>1.1 gettimeofday()</h2><p> 可与tv指向的缓冲区中返回日历时间</p>
<p>int gettimeofday(struct timeval * tv, struct timezone *tz)</p>
<p>其中tv定义如下：</p>
<p>struct timeval {</p>
<p>​    time_t tv_sec;                 //      UTC 以来的秒数</p>
<p>​    suseconds_t tv_usec;    //  微妙</p>
<p>}</p>
<p>tz为历史产物，目前已经被废弃，应始终设置为NULL。</p>
<h2 id="1-2-time"><a href="#1-2-time" class="headerlink" title="1.2 time()"></a>1.2 time()</h2><p>time() 返回Epoch以来的秒数，和gettimeofday()所返回的tv参数中的tv_sec字段的数值相同。</p>
<h2 id="1-3-时间转换函数"><a href="#1-3-时间转换函数" class="headerlink" title="1.3 时间转换函数"></a>1.3 时间转换函数</h2><p>time_t 可通过以下转换函数实现不同格式间的转换</p>
<img src="/2020/11/17/03%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91/01c_cpp/05%E6%97%B6%E9%97%B4/time.png" srcset="/img/loading.gif" lazyload class="">

<h3 id="1-3-1-ctime"><a href="#1-3-1-ctime" class="headerlink" title="1.3.1 ctime()"></a>1.3.1 ctime()</h3><p>char* ctime(const time_t *timep) 将返回一个长达26字节的字符串 (包含\n \0 结束符)，内含标准格式的日期和时间。如下所示:<br><code>Tue Nov 17 12:22:34 CST 2020</code><br>ctime函数自动的对本地时区和DST（Daylight Saving Time， 即夏令时）的设置加以考虑，返回的字符串是静态分配，下一次调用将会覆盖上一次的值。（可使用ctime_r版本替换ctime，解决静态分配问题)</p>
<h3 id="1-3-2-gmtime-和localtime-将time-t转为分解时间"><a href="#1-3-2-gmtime-和localtime-将time-t转为分解时间" class="headerlink" title="1.3.2 gmtime() 和localtime() 将time_t转为分解时间"></a>1.3.2 gmtime() 和localtime() 将time_t转为分解时间</h3><p>函数gmtime()和localtime()可将time_t 的值转换为分解时间，分解时间被置于静态结构中，其地址作为函数结果返回</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><div class="code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></div></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-function">struct tm * <span class="hljs-title">gmtime</span><span class="hljs-params">(<span class="hljs-keyword">const</span> <span class="hljs-keyword">time_t</span> *timep)</span></span><br><span class="hljs-function">struct tm * <span class="hljs-title">localtime</span><span class="hljs-params">(<span class="hljs-keyword">const</span> <span class="hljs-keyword">time_t</span> * timep)</span></span><br></code></pre></td></tr></table></figure>
<p>gmtime 可以将<code>日历时间</code>转换为UTC的分解时间，（GM来自于格林威治标准时间)<br>localtime 将考虑时区和夏令时设置，返回对应于系统本地时间的一个分解时间</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs nginx"><span class="hljs-attribute">gmtime_r</span> 和localtime_r 为两个函数的可重入版本<br></code></pre></td></tr></table></figure>
<h3 id="1-3-3-mktime-将本地分解时间转为time-t"><a href="#1-3-3-mktime-将本地分解时间转为time-t" class="headerlink" title="1.3.3 mktime() 将本地分解时间转为time_t"></a>1.3.3 mktime() 将本地分解时间转为time_t</h3><p>这一转换会忽略输入tm结构中的tm_wday和tm_yday字段。</p>
<h2 id="1-4-分解时间和打印格式之间的转换"><a href="#1-4-分解时间和打印格式之间的转换" class="headerlink" title="1.4 分解时间和打印格式之间的转换"></a>1.4 分解时间和打印格式之间的转换</h2><h3 id="1-4-1-asctime"><a href="#1-4-1-asctime" class="headerlink" title="1.4.1 asctime()"></a>1.4.1 asctime()</h3><p>char* asctime(const struct tm* timeptr) 功能等同于ctime(), 只不过接收的参数是struct tm*类型；本地时区的设置对本函数没有影响<br><code>可重入版本为asctime_r()</code></p>
<h3 id="1-4-2-strftime-更精确的打印格式转换"><a href="#1-4-2-strftime-更精确的打印格式转换" class="headerlink" title="1.4.2 strftime() 更精确的打印格式转换"></a>1.4.2 strftime() 更精确的打印格式转换</h3><p>size_t strftime(char * outstr, size_t maxsize, const char * format, cosnt struct tm* timeptr); 在分解时间转换为打印格式时，可通过format 提供更为精确的控制。令timeptr指向分解时间，strftime()会将以null结尾，由日期和时间组成的响应字符串置于outstr所指向的缓冲区中</p>
<h3 id="strptime-将打印格时间-转换为分解时间"><a href="#strptime-将打印格时间-转换为分解时间" class="headerlink" title="strptime() 将打印格时间 转换为分解时间"></a>strptime() 将打印格时间 转换为分解时间</h3><p>函数strptime() 是strftime()的逆向函数，将字符串转为分解时间<br><code>char * strptime(cosnt char * str, const char * format, struct tm * timeptr)</code></p>
<h1 id="2-进程时间"><a href="#2-进程时间" class="headerlink" title="2. 进程时间"></a>2. 进程时间</h1><p>也成为cpu时间，以时钟滴答进行计算</p>
<h2 id="times"><a href="#times" class="headerlink" title="times()"></a>times()</h2><p>clock_t times(struct tms * buf) 获取程序执行消耗的用户时间和cpu时间，tms结构体的前两个字返回调用进程到目前为止使用的用户和系统组件的cpu时间，最后两个字段返回的信息是：父进程(比如，times()的调用者)执行了系统调用wait()的所有已经终止的子进程使用的cpu时间。<br>clock_t 是用时钟计时单元为单位度量时间的整型值。我们可以调用sysconf(_SC_CLK_TCK)来获取每秒包含的时钟计时单元数，然后用这个数字除以clock_t 转换为秒</p>
<p>注意：clock_t 是有有效范围的，溢出后，times(0的返回值将再次从0开始计算)</p>
<h2 id="clock"><a href="#clock" class="headerlink" title="clock()"></a>clock()</h2><p>函数<code>clock_t clock(void);</code>  提供了一个简单的接口用于取得进程时间。它返回一个值描述了调用进程使用的总的CPU时间（包括用户和系统).</p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91/">软件开发</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/c/">c++</a>
                    
                      <a class="hover-with-bg" href="/tags/c/">c</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2020/11/20/03%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91/01c_cpp/06%E8%99%9A%E7%BB%A7%E6%89%BF/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">虚继承</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2020/11/12/04DevOps/09%E7%9B%91%E6%8E%A7%E8%BF%9B%E7%A8%8B%E7%9A%84%E5%8F%A5%E6%9F%84%E5%8F%8A%E5%90%AF%E5%8A%A8%E6%97%B6%E9%97%B4/">
                        <span class="hidden-mobile">监控进程的句柄及启动时间</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  

  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
